//
//  FSFileManager.m
//  Generic-Project
//
//  Created by Hequn on 12-8-9.
// 

#import "FSFileManager.h"
//#import "ConstantDefine.h"


static FSFileManager* pInstance;

@implementation FSFileManager

+(FSFileManager *)shareFlManager
{
    @synchronized(self){
        if(pInstance == nil)
        {
            pInstance = [[FSFileManager alloc] init];
        }
    }
    return pInstance;
}

-(BOOL)writeFileToPath:(NSString *)path fileData:(id)fData
{
    
    if(!path || [path length]==0)
    {
        NSLog(@"File path is invalid!");
        return NO;
    }
    
    if(![self checkFileExistAndCreate:path])
        return NO;
    
    BOOL ret = NO;
    if([fData isKindOfClass:[NSString class]])
    {
        NSString* fileWriter = fData;
        NSError* err;
        ret = [fileWriter writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&err];
    }
    else if([fData isKindOfClass:[NSDictionary class]] ||
            [fData isKindOfClass:[NSData class]] ||
            [fData isKindOfClass:[NSMutableArray class]])
    {
        ret = [fData writeToFile:path atomically:YES];
    }
    return ret;
}

-(BOOL)writeFileToDocumentWithName:(NSString*)fileName fileData:(id)fileData
{
    NSString* docPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    return [self writeFileToPath:docPath fileData:fileData];
}

-(id)readFileFromFilePath:(NSString*)path fileData:(id)fData
{
    if([fData isKindOfClass:[NSString class]])
    {
        NSError* err;
        fData = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
    }
    else if([fData isKindOfClass:[NSDictionary class]])
    {
        fData = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    else if([fData isKindOfClass:[NSMutableArray class]])
    {
        fData = [NSMutableArray arrayWithContentsOfFile:path];
    }
    else if([fData isKindOfClass:[NSData class]])
    {
        fData = [NSData dataWithContentsOfFile:path];
    }
    return fData;
}

-(id)readFileFromDocument:(NSString *)fileName fileData:(id)fData
{
    NSString* docPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
    return [self readFileFromFilePath:docPath fileData:fData];
}

-(BOOL)checkFileExistAndCreate:(NSString*)filePath
{
    BOOL ret = YES;
    if(([[NSFileManager defaultManager] fileExistsAtPath:filePath]) == NO)
    {
        ret = [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    return ret;
}

@end
